package com;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.util.JWTTokenUtil;
import com.util.JsonUtil;

import javax.security.sasl.AuthenticationException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 验证是否登录拦截器
 */
@WebFilter("*.do")
public class IsLoginFillter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException {
        System.out.println("过滤器执行");
        JsonUtil jsonUtil = new JsonUtil();
        GsonBuilder gsonBuilder = new GsonBuilder();
        servletResponse.setContentType("application/json;charset=utf-8");
        Gson gson = gsonBuilder.create();
        PrintWriter writer = servletResponse.getWriter();
        JWTTokenUtil jwtTokenUtil = new JWTTokenUtil();

        String decodeToken = null;
        try {
            decodeToken = jwtTokenUtil.getDecodeToken((HttpServletRequest) servletRequest);
            if(decodeToken!=null){
                filterChain.doFilter(servletRequest,servletResponse);
            }else {
                jsonUtil.setCode(1);
                jsonUtil.setMsg("用户未登录");
                String s = gson.toJson(jsonUtil);
                writer.print(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonUtil.setCode(1);
            jsonUtil.setMsg("用户未登录或未知错误"+e.getMessage());
            String s = gson.toJson(jsonUtil);
            writer.print(s);
        }


    }

    @Override
    public void destroy() {

    }
}
